package com.SMP.controller;

import com.SMP.model.*;
import com.SMP.model.httpModel.FaceMsg;
import com.SMP.model.httpModel.FaceVersion;
import com.SMP.service.ApiService;
import com.SMP.service.BroadcastService;
import com.SMP.service.PeopleService;
import com.SMP.service.class_room.AttendanceService;
import com.SMP.service.class_room.CourseService;
import com.SMP.service.class_room.EquipmentService;
import com.SMP.service.class_room.RoomService;
import com.SMP.utils.DateUtil;
import com.SMP.utils.Face;
import com.SMP.utils.Utils;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpRequest;
import org.apache.ibatis.annotations.Param;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.thymeleaf.util.StringUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

/**
 * @program: SchoolManagementPlatform
 * @description: 移动端接口
 * @author: WYHY
 * @create: 2018-12-21 16:27
 **/
@Controller
//@RequestMapping(value = "/api")
public class ApiController {

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    CourseService courseService;

    @Autowired
    RoomService roomService;

    @Autowired
    AttendanceService attendanceService;

    @Autowired
    BroadcastService broadcastService;

    @Autowired
    ApiService apiService;

    @Autowired
    PeopleService peopleService;

    /**
     * @Description: 获取设备
     * @Param: [IP]
     * @return: com.SMP.model.Msg
     * @Author: WYHY
     * @Date: 2018/11/26
     */
    @RequestMapping(value = "/selectEquipmentByIP", method = RequestMethod.POST)
    @ResponseBody
    public Msg selectEquipmentByIP(@RequestParam(value = "IP") String IP) {
        if (StringUtils.isEmpty(IP)) {
            return Msg.fail();
        } else if (Utils.isIP(IP)) {
            List<Course> courses = new ArrayList<Course>();
            List<Course> toDayCourses = new ArrayList<Course>();
            List<Attendance> attendances = new ArrayList<Attendance>();
            Course nowCourses = null;
            List<String> filename = new ArrayList<String>();
            Room room = new Room();
            People people = new People();
            EquipmentExample equipmentExample = new EquipmentExample();
            EquipmentExample.Criteria criteria = equipmentExample.createCriteria();
            criteria.andEquipmentIpEqualTo(IP);
            Equipment equipment = equipmentService.selectEquipmentE(equipmentExample);
            if (equipment == null) {
                Equipment ea = new Equipment();
                ea.setEquipmentIp(IP);
                try {
                    InetAddress address = InetAddress.getByName(IP);
                    String name = address.getHostName();
                    ea.setEquipmentName(name);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ea.setEquipmentState("2");
                ea.setStandby1("1");
                equipmentService.addEquipment(ea);
            } else {
                List<Room> rooms = roomService.selRoomByEid(equipment.getEquipmentId());
                if (rooms.size() > 0) {
                    Course course = new Course();
                    course.setStandby2(rooms.get(0).getId());
                    courses = courseService.selCourse(course);
                    room = rooms.get(0);
                }
                room.setInputTime(null);
                filename = broadcastService.getFileName("Carousel/");
                int week = LocalDate.now().getDayOfWeek().getValue();
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                Date now = null;
                Date beginTime = null;
                Date endTime = null;
                for (Course course : courses) {
                    if (course.getWeek() == week) {
                        toDayCourses.add(course);
                    }
                }

                try {
                    for (int i = 0; i < toDayCourses.size(); i++) {
                        now = df.parse(df.format(new Date()));
                        beginTime = df.parse(i - 1 >= 0 ? toDayCourses.get(i - 1).getClassOver().toString() : "00:00");
                        endTime = df.parse(toDayCourses.get(i).getClassOver().toString());
                        if (DateUtil.belongCalendar(now, beginTime, endTime)) {
                            nowCourses = toDayCourses.get(i);
                            break;
                        } else {
                            nowCourses = null;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (nowCourses != null) {
                    people = peopleService.selByPrimaryKey(nowCourses.getName());
//                    attendanceService.addAttendance(people, nowCourses, "2");
//                    People student = new People();
//                    student.setClasss(nowCourses.getClasss());
//                    student.setGrade(nowCourses.getGrade());
//                    for (People attend : peopleService.selPeoples(student)) {
//                        attendanceService.addAttendance(attend, nowCourses, "2");
//                    }
//                    Attendance attendance = new Attendance();
//                    attendance.setTime(new Date());
//                    attendance.setWeek(nowCourses.getWeek() + "");
//                    attendance.setLessonsId(nowCourses.getLessonsNo() + "");
//                    attendances = attendanceService.selAttendance(attendance);
                } else {
                    people = null;
                    attendances = null;
                }

            }
            return Msg.success()
                    .add("course", courses)
                    .add("toDayCourses", toDayCourses)
                    .add("nowCourse", nowCourses)
                    .add("room", room)
                    .add("teacher", people)
//                    .add("attendances", attendances)
                    .add("filename", filename);
        } else {
            return Msg.fail();
        }
    }

    /**
     * @Description: 查询应用版本
     * @Param: []
     * @return: void
     * @Author: WYHY
     * @Date: 2018/12/29
     */
    @RequestMapping(value = "/App/Version", method = RequestMethod.POST)
    @ResponseBody
    public void version() {
        apiService.selAppVerson();
    }

    /**
     * @Description: 获取最近5天的新闻时间
     * @Param: []
     * @return: com.SMP.model.Msg
     * @Author: WYHY
     * @Date: 2018/12/29
     */
    @RequestMapping(value = "/NewsTime", method = RequestMethod.POST)
    @ResponseBody
    public Msg newsTime() {
        List<News> news = apiService.selNewsTime();
        if (news.size() > 0) {
            return Msg.success().add("news", news);
        } else {
            return Msg.fail();
        }
    }

    /**
     * @Description: 人脸识别接口
     * @Param: [request]
     * @return: com.SMP.model.Msg
     * @Author: WYHY
     * @Date: 2018/12/29
     */
    @RequestMapping(value = "/getFace", method = RequestMethod.POST)
    @ResponseBody
    public Msg getFace(HttpServletRequest request) {
        System.out.println("---------------------------人脸接口开始---------------------------");
        List<People> result=new ArrayList();
        String img64="";
        try {
            JSONObject jsonObject=new JSONObject(Utils.getRequestBody(request));
            img64=jsonObject.getString("file");
            System.out.println("---------------------------人脸base64："+img64+"---------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (img64.length()>0){
            String faceid= null;
            try {
                faceid = Face.scannerFace(img64,"testClazz",85.5,10);
            } catch (Exception e) {
                System.out.println("---------------------------第三方人脸接口报错---------------------------");
            }
            if (faceid!=null){
                System.out.println("---------------------------人脸id："+faceid+"---------------------------");
                People people=peopleService.selectFace(faceid);
                people.setInputTime(null);
                Course course=new Course();
                course.setName(people.getId());
                List<Course> courses=courseService.selCourse(course);
                LocalTime now=LocalTime.now();
                System.out.println("---------------------------当前时间："+now+"---------------------------");
                if (courses.size()>0&&now.isAfter(courses.get(0).getHaveClass().toLocalTime().minusMinutes(30))&&now.isBefore(courses.get(0).getClassOver().toLocalTime())&&people.getProfessional().equals("1")){
                    result.add(people);
                    System.out.println("---------------------------人脸接口符合条件开门---------------------------");
                }else if (people.getProfessional().equals("3")){
                    result.add(people);
                    System.out.println("---------------------------人脸接口超级管理员开门---------------------------");
                }
                System.out.println("---------------------------人脸接口结束---------------------------");
                if (result.size()>0){
                    return Msg.success().add("face",result);
                }else {
                    return Msg.fail();
                }
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail();
        }

    }

    /**
     * 考勤接口
     * @author WYHY
     *
     * */
    @RequestMapping("/toAttendance")
    @ResponseBody
    public Msg addAttendance(String img64,String dbname,String courseid){
        String face= null;
        try {
            face = Face.scannerFace(img64,dbname,85.5,10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (face!=null){
            People people=peopleService.selectFace(face);
            Course course=courseService.selCourseById(courseid);
            if (people!=null&&course!=null){
                attendanceService.addAttendance(people,course,"1");
                return Msg.success().add("faceresult","查询成功");
            }else {
                return Msg.fail().add("faceresult","人员或课程查询失败");
            }
        }else {
            return Msg.fail().add("faceresult","人脸识别失败");
        }
    }

    @RequestMapping("/getAPIVersion")
    @ResponseBody
    public Msg getAPIVersion(@RequestParam("infojson")String infojson){
        System.out.println("授权信息"+infojson);
        String data=infojson.substring(infojson.lastIndexOf("："),infojson.length());
        String ip=infojson.substring(0,infojson.lastIndexOf("："));
        FaceVersion faceVersion= com.alibaba.fastjson.JSONObject.parseObject(data,FaceVersion.class);
        EquipmentExample example=new EquipmentExample();
        EquipmentExample.Criteria criteria= example.createCriteria();
        if (ip!=null&&!StringUtils.isEmpty(ip)){
            criteria.andEquipmentIpEqualTo(ip);
        }
        Equipment equipment=equipmentService.selectEquipmentE(example);
        equipment.setStandby6(faceVersion.getDeviceSignature());
        equipmentService.updateEquipment(equipment);
        return  Msg.success();
    }
}
